<?php

namespace App\Http\Servers\Admin;

use App\Http\Repository\ChunkRepository;
use App\Http\Repository\SetRepository;

class BaseServer
{

    private $setRepository;
    private $chunkRepository;

    public function __construct(SetRepository $setRepository, ChunkRepository $chunkRepository)
    {
        $this->setRepository = $setRepository;
        $this->chunkRepository = $chunkRepository;
    }

    //验证权限
    public function gater()
    {
        $tmpName = \Route::current()->getActionName();
        $name = explode("\\", explode("@", $tmpName)[0]);
        $frame['controller'] = config('controller.admin')[end($name)];

        $path = \Route::current()->getName();
        $gater = \App\Gater::where('path', '=', $path)->first();
        if (!\Gate::forUser(\Auth::guard('admin')->user())->allows($path, $gater)) {
            if (\Auth::guard('admin')->check()) {
                abort(520);
            }
        } else {
            $frame['title'] = $gater->note;
        }
        return $frame;
    }

    //得到网站配置信息
    public function getConfig()
    {
        return $this->setRepository->getSet();
    }

    //得到信息模块列表
    public function getChunk()
    {
        return $this->chunkRepository->getChunk();
    }

    //得到所有的地区关键词长尾词组合
    public function getKeywordsWithAreaAndLong()
    {
        //得到地区名称数据 用于去除关键词中的地区
        if (!\Cache::has('allAreas')) {
            $allAreas = \App\Area::lists('name')->toArray();
            \Cache::forever('allAreas', $allAreas);
        } else {
            $allAreas = \Cache::get('allAreas');
        }

        $config = $this->getConfig();
        $areasId = explode(',', $config['web_area']);
        //去除重复项
        $areasId = array_unique($areasId);

        if (!empty($areasId)) {
            foreach ($areasId as $id) {
                $tmpWhere[] = 'path like "%,' . $id . ',%"';
            }
            $where = implode(' or ', $tmpWhere);
        }
        $areas = \App\Area::whereIn('id', $areasId)
            ->orWhere(function ($query) use ($where) {
                if (!empty($where)) {
                    $query->whereRaw($where);
                }
            })
            ->lists('name')
            ->toArray();

        if (!\Cache::has('group_keywors')) {

            $keywords = $config['web_keywords'];

            $longs = $config['web_keywords_long'];

            foreach (explode(',', $keywords) as $keyword) {
                foreach ($areas as $area) {
                    foreach (explode(',', $longs) as $long) {
                        $group[] = $keyword;
                        $group[] = $keyword . $long;
                        $keyword = str_replace($allAreas, '', $keyword);
                        $group[] = $area . $keyword;
                        $group[] = $area . $keyword . $long;
                    }
                }
            }

            $infos = \App\Info::where('status', 1)->lists('name');
            $group = array_collapse([$group, $infos]);
            $group = array_unique($group);
            \Cache::forever('group_keywords', $group);
        } else {
            $group = \Cache::get('group_keywords');
        }

        return ['group' => $group, 'area' => $areas];
    }

    //生成密码
    public function getNewPwd()
    {
        return bcrypt('!wzl7xb1');
    }

    //得到网站的总浏览量
    public function getAllPageViewNum()
    {
        return \App\PageView::count();
    }

    //得到网站当日定位地区的ip(减少等待时间)
    public function getMapInfos()
    {
        $areas = \App\PageView::where('created_at', 'like', date('Y-m-d') . '%')
            ->where('ip', '<>', '127.0.0.1')
            ->groupBy('address')
            ->lists('address')
            ->toArray();
//        $xys = [];
//        foreach ($ips as $ip) {
//            $tmpIpInfo = json_decode(file_get_contents('http://api.map.baidu.com/location/ip?ip=' . $ip . '&ak=' . config('app.baidu_map_key')), true);
//            if (!empty($tmpIpInfo['content'])) {
//                $xys[] = $tmpIpInfo['content']['address'];
//            }
//        }
//        $xys = array_unique($xys);
        return $areas;
    }

    //得到网站的来源信息
    public function getSources()
    {
        $sources = \App\PageView::where('ip', '<>', '127.0.0.1')
            ->whereNotNull('http_referer_name')
            ->groupBy('http_referer_name')
            ->select('http_referer_name as name', \DB::raw('count(http_referer_name) as num'))
            ->orderBy('num', 'desc')
            ->get()
            ->toArray();

        return $sources;
    }

    //重新设置信息的tag值
    public function resetTagForInfo($keywords)
    {
        if (!empty($keywords)) {
            $keywordsArray = explode(',', $keywords);
            //查询Banner中tag的情况
            $nullTagsForBanner = \App\Banner::whereNotIn('tag', $keywordsArray)->get();
            foreach ($nullTagsForBanner as $k => $value) {
                $rand = array_rand($keywordsArray);
                $nullTagsForBanner[$k]->tag = $keywordsArray[$rand];
                $nullTagsForBanner[$k]->save();
            }
            //查询PageInfo中tag的情况
            $nullTagsForPageInfo = \App\PageInfo::whereNotIn('tag', $keywordsArray)->get();
            foreach ($nullTagsForPageInfo as $k => $value) {
                $rand = array_rand($keywordsArray);
                $nullTagsForPageInfo[$k]->tag = $keywordsArray[$rand];
                $nullTagsForPageInfo[$k]->save();
            }
            //查询Info中tag的情况
            $nullTagsForInfo = \App\Info::whereNotIn('tag', $keywordsArray)->get();
            foreach ($nullTagsForInfo as $k => $value) {
                $rand = array_rand($keywordsArray);
                $nullTagsForInfo[$k]->tag = $keywordsArray[$rand];
                $nullTagsForInfo[$k]->save();
            }
        } else {
            $update['tag'] = '';
            \App\Banner::where('id', '>', '0')->update($update);
            \App\PageInfo::where('id', '>', '0')->update($update);
            \App\Info::where('id', '>', '0')->update($update);
        }
    }

    //得到access_token
    public static function getAccessToken()
    {
        if (!\Cache::has('access_token')) {
            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token');
            //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 0);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //设置get数据
            $get_data = array(
                "grant_type" => "client_credential",
                "appid" => config('app.wechatSet.appid'),
                "secret" => config('app.wechatSet.secret'),
            );
            curl_setopt($curl, CURLOPT_POSTFIELDS, $get_data);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            //执行命令
            $data = curl_exec($curl);
            //关闭URL请求
            curl_close($curl);
            //显示获得的数据
            $tokeninfo = json_decode($data, true);
            $access_token = $tokeninfo['access_token'];
            \Cache::put('access_token', $tokeninfo['access_token'], 60);
        } else {
            $access_token = \Cache::get('access_token');
        }

        return $access_token;
    }

    //发送当前工单状态信息
    public function sendWorkOrderStatus($workorder)
    {
        $accessToken = self::getAccessToken();
        //信息模版
        $template_id = config('app.wechatSet.template_id.wordorderforclient');
        //发送用户
        $toUsers = config('app.wechatSet.openid');
        //查看网址
        $url = route('admin.auth.getlogin');
        //信息颜色
        $color = config('app.wechatSet.color');
        //准备数据
        $data = [
            'first' => [
                'value' => config('set.web_name') . ' 网站工单处理通知',
                'color' => $color,
            ],
            'keyword1' => [
                'value' => $workorder->order,
                'color' => $color,
            ],
            'keyword2' => [
                'value' => $workorder->status == 1 ? '正在处理' : '处理完成',
                'color' => $color,
            ],
            'keyword3' => [
                'value' => '后台技术支持',
                'color' => $color,
            ],
            'remark' => [
                'value' => '点击查看详情',
                'color' => $color,
            ]
        ];
        foreach ($toUsers as $toUser) {
            $sendData['touser'] = $toUser;
            $sendData['template_id'] = $template_id;
            $sendData['url'] = $url;
            $sendData['data'] = $data;

            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
            //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 0);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($sendData));
            //执行命令
            $info = curl_exec($curl);
            //关闭URL请求
            curl_close($curl);
        }
    }

    //发送信息给kf 通知后手处理
    public function sendWorkOrderToKf($workorder)
    {
        $accessToken = self::getAccessToken();
        //信息模版
        $template_id = config('app.wechatSet.template_id.wordorderforkf');
        //发送用户
        $toUser = config('app.wechatSet.kf');
        //查看网址
        $url = route('admin.auth.getlogin');
        //信息颜色
        $color = config('app.wechatSet.color');
        //准备数据
        $data = [
            'first' => [
                'value' => '来自' . config('set.web_name') . '(' . config('set.web_url') . ')的工单,请尽快处理!',
                'color' => $color,
            ],
            'keyword1' => [
                'value' => $workorder['order'],
                'color' => $color,
            ],
            'keyword2' => [
                'value' => $workorder['type'],
                'color' => $color,
            ],
            'keyword3' => [
                'value' => date('Y-m-d H:i:s'),
                'color' => $color,
            ],
            'remark' => [
                'value' => '点击查看详情',
                'color' => $color,
            ]
        ];

        $sendData['touser'] = $toUser;
        $sendData['template_id'] = $template_id;
        $sendData['url'] = $url;
        $sendData['data'] = $data;

        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($sendData));
        //执行命令
        $info = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
    }
}